package controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.MyUser;
import service.UserService;
import util.Result;

import java.util.List;

/**
 * author: 李林凯
 * time:2025/6/17 09:12
 **/
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user/list")
    public String getUserByPage(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "3") int limit,
                                Model model) {
        //算页数的
        int totalCount = userService.getUserCount();
        int totalPage = (int)Math.ceil((double)totalCount / (double)limit);
        //判断page是否合法
        if(page < 1 ) page=1;
        if(page > totalPage && totalCount>0) page = totalPage;
        //分页参数
        int offset = (page - 1) * limit;

        List<MyUser> userList = userService.getUserByPage(offset, limit);
        model.addAttribute("userList", userList);
        model.addAttribute("page", page);
        model.addAttribute("total", totalCount); // 修正：传递总记录数
        model.addAttribute("size", limit);

        return "userList";
    }
    //增
    @GetMapping("/user/add")
    public String show() {
        return "addUser";
    }
    @PostMapping("/user/add")
    public String addUser(MyUser user) {
        userService.insertUser(user);
        return "redirect:/user/list";
    }
    //删除
    @PostMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable int id) {
        userService.deleteUserById(id);
        return "redirect:/user/list";
    }
    //修改的返回
    @PostMapping("/user/update")
    public String updateUser(MyUser user,Model model) {
        model.addAttribute("user", user);
        userService.updateUser(user);
        return "redirect:/user/list";
    }
    //编辑的页面
    @GetMapping("/user/edit/{id}")
    public String selectUser(@PathVariable int id, Model model) {
        MyUser user = userService.selectUserById(id);
        model.addAttribute("user", user);
        return "editUser";
    }
    @PostMapping("/user/edit")
    public String editUser(MyUser user,Model model) {
        userService.updateUser(user);
        model.addAttribute("user", user);
        return "redirect:/user/list";
    }
    //测试异常
    @GetMapping("/testError")
    public String testError() {
        throw new RuntimeException("测试异常信息");
    }
}
